package main.chapter6.async

import main.chapter6.log
import java.io.ByteArrayOutputStream
import java.net.URL
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.startCoroutine
import kotlin.coroutines.suspendCoroutine

fun asyncCoroutine(block: suspend () -> Unit) {
    block.startCoroutine(ContextContinuation(AsyncContext()))
}
//封装一个通用的耗时操作的方法
suspend fun <T> startTimeConsumingOperations(block: () -> T) = suspendCoroutine<T> { continuation ->
    AsyncTask {
        try {
            continuation.resume(block())
        } catch (e: Exception) {
            continuation.resumeWithException(e)
        }
    }.execute()
}

fun startDownloadImage(url: String): ByteArray {
    log("异步任务开始前")
    log("耗时操作，下载图片")
    val imgUrl = URL(url)
    //打开连接
    val urlConnection = imgUrl.openConnection()
    val inputStream = urlConnection.getInputStream()
    //将inputStream解析为Byte[]
    val output = ByteArrayOutputStream()
    val buffer = ByteArray(4096)
    while (true) {
        val result = inputStream.read(buffer)
        if (result == -1) {
            break
        } else {
            output.write(buffer, 0, result)
        }
    }
    return output.toByteArray()
}
//suspend fun startDownloadImage(url: String) = suspendCoroutine<ByteArray> { continuation ->
//    //    //通过uiContinuation包装来切换回主线程
////    val uiContinuationWrapper = UIContinuationWrapper<ByteArray>(continuation)
//    log("异步任务开始前")
//    AsyncTask {
//        try {
//            log("耗时操作，下载图片")
//            val imgUrl = URL(url)
//            //打开连接
//            val urlConnection = imgUrl.openConnection()
//            val inputStream = urlConnection.getInputStream()
//            //将inputStream解析为Byte[]
//            val output = ByteArrayOutputStream()
//            val buffer = ByteArray(4096)
//            while (true) {
//                val result = inputStream.read(buffer)
//                if (result == -1) {
//                    break
//                } else {
//                    output.write(buffer, 0, result)
//                }
//            }
//            if (output.toByteArray() != null) {
//                //通过continuation将结果或者异常传递出去
//                continuation.resume(output.toByteArray())
//            } else {
//                continuation.resumeWithException(Exception("图片请求异常"))
//            }
//        } catch (e: Exception) {
//            continuation.resumeWithException(e)
//        }
//    }.execute()
//}